<?php 
/*
 * Pagination Helper CakePHP framework.
 * Copyright (c) 2005 Garrett J. Woodworth : gwoo@rd11.com
 * rd11,inc : http://rd11.com
 *
 * @author      gwoo <gwoo@rd11.com>
 * @version     0.10.8.2176
 * 
 */

class PaginationHelper  {
	

	var $helpers = array('Html','Ajax','appHtml');
	var $_details = array();
	var $show_select = array();
	var $total = '0';
	var $style = 'html';
	var $link = '';
	var $show = array();
	var $page = '1';
	var $direction = 'desc';
	var $pageCount='0';
	
	var $updateId = 'ajax_update';
	var $loadingId = 'loading';
	
	
	/**
	 * Sets the default pagination options. 
	 *
	 * @param array $paging an array detailing the page options
	 */
	function set($paging,$show_select=true)
	{
		if(!empty($paging))
		{
			$this->style = isset($paging['style']) ? $paging['style'] : 'html';
			$this->link = (isset($paging['link']) && isset($paging['params'])) ? $paging['link'].$paging['params'] : $paging['link'];
			$this->show = isset($paging['show']) ? $paging['show'] : array();
			$this->page = isset($paging['page']) ? $paging['page'] : '1';
			$this->direction = isset($paging['direction']) ? $paging['direction'] : 'desc';
			$this->show_select = isset($paging['show_select']) ? $paging['show_select'] : array();
			$pageCount = ceil($paging['count'] / $paging['limit'] );
			$this->pageCount = $pageCount;
							
			//echo $paging['count'];	
			$this->_details = array(
						'page'=>$paging['page'],
						'recordCount'=>$paging['count'],
						'pageCount' =>$pageCount,
						'next'=> ($paging['page'] < $pageCount) ? $paging['page']+1 : '',
						'previousPage'=> ($paging['page']>1) ? $paging['page']-1 : '',
						'limit'=>$paging['limit']
						);
						
		}
		
		$return = $this->load_image($this->loadingId);
		if($show_select){
			$return .= $this->showSelect();
		}
		if(!empty($paging) && $paging['count'] > $paging['show'][0])
		{
			$return .=$this->showPage();
		}
		return $return;
	}
	/**
	* Displays limits for the query 
	*
	* @param string $text - text to display before limits
	* @param string $seperator - display a seperate between limits
	*
	**/
	function show($text=null, $seperator=null)
	{
		if (empty($this->_details)) { return false; }
		if (!empty($this->_details['recordCount']))
		{
			$t = '';
			if(is_array($this->show))
			{
				$t = $text.$seperator;
				foreach($this->show as $value)
				{
					if($value < ($this->_details['recordCount'] + $this->_details['limit']))
					{
						$link = preg_replace('/show=(.*?)&/','show='.$value.'&',$this->link);
						if($this->_details['limit'] == $value)
						{
							$t .= '<span class="linow">'.$value.'</span>'.$seperator;
						}
						else
						{	
							if($this->style == 'ajax')
							{	
								$t .= $this->Ajax->link($value, $link.$this->_details['page'], array("update" => $this->updateId, 'loading' => "Element.show('".$this->loadingId."');", 'complete' => "Element.hide('".$this->loadingId."');", "method"=>"get")).$seperator;
							}
							else
							{
								$t .= $this->Html->link($value,$link.$this->_details['page']).$seperator;
							}
						}
					}
				}
			}
			return $t;
		}
		return false;
		
	}
	/**
	* Displays current result information 
	*
	* @param string $text - text to preceeding the number of results
	*
	**/
	function result($text)
	{
		if (empty($this->_details)) { return false; }
		if ( !empty($this->_details['recordCount']) )
		{
			if($this->_details['recordCount'] > $this->_details['limit'])
			{
				$start_row = $this->_details['page'] > 1 ? ($this->_details['page']-1)*$this->_details['limit']: '1';
				$end_row = ($this->_details['recordCount'] < ($start_row + $this->_details['limit']-1)) ? $this->_details['recordCount'] : ($start_row + $this->_details['limit']-1);
				return $text.$start_row.'-'.$end_row.' of '.$this->_details['recordCount'];
			}
			else
			{
				return $text.$this->_details['recordCount'];
			}
		}
		return false;
	}
	/**
	* Returns a list of page numbers seperated by $seperator
	*
	* @param string $seperator - defaults to null
	*
	**/
	function numbers($seperator=null)
	{
		if (empty($this->_details) || $this->_details['pageCount'] == 1) { return false; }
		$t = '';
		
		
		$page=($this->_details['page']-5)>0?($this->_details['page']-5):1;		
		if($this->pageCount-$this->_details['page']<5){
			$page = ($this->pageCount-10)>0?($this->_details['page']-10+$this->pageCount-$this->_details['page']):1;
		}				 
		  for($i=0;$i<11&&$page<=$this->_details['pageCount'];$i++,$page++) 
		  {		  	 
			 if($page == $this->_details['page'])
			 {
				$t .= '<span>'.$page.'</span>&nbsp;';
			 }
			 else
			 {
				if($this->style == 'ajax')
				{	
					$t .= $this->Ajax->link($page, $this->link.$page, array("update" => $this->updateId, 'loading' => "Element.show('".$this->loadingId."');", 'complete' => "Element.hide('".$this->loadingId."');", "method"=>"get"));
				}
				else
				{
					$t .= $this->Html->link($page,$this->link.$page);
				}
			 }			 
		  } 
				
		return $t;
	}
	/**
	* Returns a "Google style" list of page numbers
	*
	* @param string $separator - defaults to null
	* @param string $prefix - defaults to null. If set, displays prefix before page links.
	* @param int $pageSetLength - defaults to 10. Maximum number of pages to show.
	* @param string $prevLabel - defaults to null. If set, displays previous link.
	* @param string $nextLabel - defaults to null. If set, displays next link.
	*
	**/
	function googleNumbers($separator=null, $prefix=null, $pageSetLength=10, $prevLabel=null, $nextLabel=null)
	{
		if (empty($this->_pageDetails) || $this->_pageDetails['pageCount'] == 1) { return false; }

		$t = array();

		$modulo = $this->_pageDetails['page'] % $pageSetLength;
		if ($modulo)
		{ // any number > 0
			$prevSetLastPage = $this->_pageDetails['page'] - $modulo;
		} 
		else 
		{ // 0, last page of set
			$prevSetLastPage = $this->_pageDetails['page'] - $pageSetLength;
		}
		//$nextSetFirstPage = $prevSetLastPage + $pageSetLength + 1;

		if ($prevLabel) $t[] = $this->prevPage($prevLabel);

		// loops through each page number
		$pageSet = $prevSetLastPage + $pageSetLength;
		if ($pageSet > $this->_pageDetails['pageCount']) $pageSet = $this->_pageDetails['pageCount'];
		
		for ($pageIndex = $prevSetLastPage+1; $pageIndex <= $pageSet; $pageIndex++)
		{
			if ($pageIndex == $this->_pageDetails['page'])
			{
				$t[] = '<span class="linow">'.$pageIndex.'</span>';
			}
			else
			{
				if($this->style == 'ajax')
				{
					$t[] = $this->Ajax->link($pageIndex,$this->link.$pageIndex, array("update" => $this->updateId, 'loading' => "Element.show('".$this->loadingId."');", 'complete' => "Element.hide('".$this->loadingId."');", "method"=>"get"));
				} 
				else 
				{
					$t[] = $this->Html->link($pageIndex,$this->link.$pageIndex);
				}
			}
		}

		if ($nextLabel) $t[] = $this->nextPage($nextLabel);

		$t = implode($separator, $t);

		return $prefix.$t;
	}
	/**
	* Displays a link to the previous page, where the page doesn't exist then
	* display the $text
	*
	* @param string $text - text display: defaults to next
	*
	**/
	function prev($text='prev')
	{
		if (empty($this->_details)) { return false; }
		if ( !empty($this->_details['previousPage']) )
		{
			if($this->style == 'ajax')
			{	
				return $this->Ajax->link($text, $this->link.$this->_details['previousPage'], array("class" => "btPrev", "update" => $this->updateId,  'loading' => "Element.show('".$this->loadingId."');", 'complete' => "Element.hide('".$this->loadingId."');", "method"=>"get"),null,false);
			}
			else
			{
				return $this->Html->link($text,$this->link.$this->_details['previousPage']);
			}
		}	
		return false;
	}
	/**
	* Displays a link to the next page, where the page doesn't exist then
	* display the $text
	*
	* @param string $text - text to display: defaults to next
	*
	**/
	function next($text='next')
	{
		if (empty($this->_details)) { return false; }
		if (!empty($this->_details['next']))
		{
			if($this->style == 'ajax')
			{	
				return $this->Ajax->link($text, $this->link.$this->_details['next'], array("class" => "btNext", "update" => $this->updateId, 'loading' => "Element.show('".$this->loadingId."');", 'complete' => "Element.hide('".$this->loadingId."');", "method"=>"get"),null,false);
			}
			else
			{
				return $this->Html->link($text,$this->link.$this->_details['next']);
			}
		}	
		return false;
	}
	
	/** 
	* Displays a link to the first page, where the page doesn't exist then
	* display the $text
	*
	* @param string $text - text to display: defaults to next
	*
	**/	
	function first($text='first')
	{
		if (empty($this->_details)) { return false; }
		if ( $this->page!="1" )
		{
			if($this->style == 'ajax')
			{	
				return $this->Ajax->link($text, $this->link."1", array("class"=>'btTop', "update" => $this->updateId,  'loading' => "Element.show('".$this->loadingId."');", 'complete' => "Element.hide('".$this->loadingId."');", "method"=>"get"),null,false);
			}
			else
			{
				return $this->Html->link($text,$this->link."1");
			}
		}	
		return false;
	}
	
	/**
	* Displays a link to the last page, where the page doesn't exist then
	* display the $text
	*
	* @param string $text - text to display: defaults to next
	*
	**/
	function last($text='last')
	{
		if (empty($this->_details)) { return false; }
		if ( $this->page!=$this->pageCount && $this->pageCount!=1)
		{
			if($this->style == 'ajax')
			{	
				return $this->Ajax->link($text, $this->link.$this->pageCount, array("class" => "btEnd" , "update" => $this->updateId, 'loading' => "Element.show('".$this->loadingId."');", 'complete' => "Element.hide('".$this->loadingId."');", "method"=>"get"),null,false);
			}
			else
			{
				return $this->Html->link($text,$this->link.$this->pageCount);
			}
		}	
		return false;
	}

	/**
	* Displays a link for sorting
	* 
	*
	* @param string $name - text to display
	* @param array $sort - array with the field to sort and default direction
	*
	**/
	function sortLink($name, $sort, $html_options = null) 
	{
		if(isset($sort[0]))
		{
			$newlink = preg_replace('/sort=(.*?)&/','sort='.$sort[0].'&',$this->link.$this->page);
			$sort[1] = ($this->direction == 'desc') ? 'asc' : 'desc';
		}
		else
		{
			$newlink = $this->link.$this->page;
		}
		
		if(!empty($sort[1]))
		{
			$newlink = preg_replace('/direction=(.*?)&/','direction='.$sort[1].'&',$newlink);
		}
		
		if($this->style == 'ajax')
		{
			return $this->Ajax->link($name, $newlink, array("update" => $this->updateId, 'loading' => "Element.show('".$this->loadingId."');", 'complete' => "Element.hide('".$this->loadingId."');", "method"=>"get"));
		}
		else
		{
			return $this->Html->link($name, $newlink);
		}
	}
	
	function deleteLink($id, $text, $confirm = "Are you sure you want to delete?", $replace = null) 
	{
		$params = (isset($this->params['pass'])) ? join('/',$this->params['pass']) : null;
		$action = ($replace) ? $replace : $this->action;
		$newlink = preg_replace('/'.$action.'/','delete/'.$id,$this->link.$this->page);
		
		if($this->style == 'ajax')
		{
			return $this->Ajax->link($text, $newlink, array("update" => $this->updateId, 'loading' => "Element.show('".$this->loadingId."');", 'complete' => "Element.hide('".$this->loadingId."');", "confirm"=>$confirm, "method"=>"get"),null,false);
		}
		else
		{
			return $this->Html->link($text, $newlink);
		}
	}

	function statusLink($id, $status, $text, $confirm = "Are you sure you want to delete?", $replace = null) 
	{
		$altstatus = ($status === '1') ? 0 : 1;

		$params = (isset($this->params['pass'])) ? '/'.join('/',$this->params['pass']) : null;
		$action = ($replace) ? $replace : $this->action;
		$newlink = preg_replace('/'.$action.'/','status/'.$id.'/'.$altstatus.$params,$this->link.$this->page);
			
		if($this->style == 'ajax')
		{
			return $this->Ajax->link($text[$status], $newlink, array("update" => $this->updateId, 'loading' => "Element.show('".$this->loadingId."');", 'complete' => "Element.hide('".$this->loadingId."');", "confirm"=>$confirm, "method"=>"get"));
		}
		else
		{
			return $this->Html->link($text[$status], $newlink);
		}
	}
	
	function current()
	{
		$t = '?';
		foreach($this->params['url'] as $key=>$value)
		{
			$t .= ($key != 'url') ? $key.'='.$value.'&' : null;
		}
		return $t;
	}
	function showSelect($selectAttr=array('style'=>'width:50px;')){
		$selectAttr['onchange']="new function(){new Ajax.Updater('ajax_update','".$this->link."1',{onLoading:function(request){Element.show('loading');},onComplete:function(request){Element.hide('loading');},asynchronous:true,evalScripts:true,parameters:Form.Element.serialize('PageShowPageSelect'),requestHeaders:['X-Update', 'ajax_update']})}";
		$return = "１ページ表示数 ".$this->Html->selectTag('PageShow/PageSelect',$this->show_select,$this->show['0'],$selectAttr,null,false)."&nbsp;&nbsp;";
		return $return;
	}
	
	function showPage($prev="前へ",$next="次へ",$first="最前",$last="最後"){
		$return = "";
		
		if(!empty($first))
			$return .= $this->first("最前");
		if(!empty($prev))
			$return .= $this->prev("前へ");
		$return .= $this->numbers();
		if(!empty($next))
			$return .= $this->next("次へ");
		if(!empty($last))
			$return .= $this->last("最後");
		return $return;
	}
	
	function load_image($loading="loading"){
		$return = "";
		$return .= "<span id=\"$loading\" style=\"display:none;\">";
		$return .= "<img src=\"/images/spinner.gif\" align=\"texttop\" />";
		$return .= "</span>";
		return $return;
	}
	
}
?>